package edu.neusoft.yiqibike.controller;

import com.baomidou.mybatisplus.plugins.Page;
import edu.neusoft.yiqibike.common.entity.mysql.IpRecord;
import edu.neusoft.yiqibike.common.entity.mysql.OperationLog;
import edu.neusoft.yiqibike.common.entity.vo.IpRecordVo;
import edu.neusoft.yiqibike.common.entity.vo.Response;
import edu.neusoft.yiqibike.common.exception.ArgumentVerifyException;
import edu.neusoft.yiqibike.service.IOperationLogService;
import edu.neusoft.yiqibike.service.IPManagerService;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;

/**
 * User：lyc
 * Date：2017-12-16
 * Time：20:52
 * Description：
 */
@RestController
@RequestMapping("/sys/ip")
public class IPManagerController {
    @Autowired
    private IPManagerService ipManagerService;
    @Autowired
    private IOperationLogService operationLogService;

    @PostMapping("/list")
    @RequiresRoles("root")
    public Response<Page<IpRecordVo>> getIPList(@RequestBody Page<IpRecord> page) {
        return Response.success(ipManagerService.getIPList(page));
    }

    @PostMapping("/hide/list")
    public Response<Page<IpRecordVo>> getHideIPList(@RequestBody Page<IpRecordVo> page) {
        return Response.success(ipManagerService.getHideIPList(page));
    }

    @PostMapping("/limit")
    public Response<String> limit(@RequestBody IpRecord ipRecord) {
        if (Objects.isNull(ipRecord) || Objects.isNull(ipRecord.getId()) || Objects.isNull(ipRecord.getIsEnable())) {
            throw new ArgumentVerifyException("检测到非法参数");
        }
        ipManagerService.invertIsEnable(ipRecord.getId(), ipRecord.getIsEnable());
        return Response.success();
    }

    @PostMapping("/{ip}/log")
    public Response<Page<OperationLog>> log(@PathVariable String ip, @RequestBody Page<OperationLog> page) {
        return Response.success(operationLogService.getLogByIP(page, ip));
    }

    @PutMapping("/{ip}")
    public Response<String> add(@PathVariable String ip) {
        ipManagerService.addIP(ip);
        return Response.success();
    }

    @PostMapping
    public Response<String> delete(@RequestBody List<String> ids) {
        if (CollectionUtils.isEmpty(ids)) {
            return Response.failed("请选中待删除的IP");
        }
        ipManagerService.deleteBatch(ids);
        return Response.success();
    }
}
